using Services;
using System.Collections.Generic;
using UnityEngine;

public class WindowLight : MonoBehaviour
{
    [SerializeField]
    private EBearing bearing;
    private MyLight2D myLight2D;
    private Clock clock;

    [SerializeField]
    private float width;
    [SerializeField]
    private float height;

    private Vector3 bottom1, bottom2;
    private readonly List<Vector3> windowOutline = new List<Vector3>();
    private readonly List<Vector3> lightOutline = new List<Vector3>();
    private GeometryTool.Comparer_Vector2_Clockwise comparer;

    private void Awake()
    {
        myLight2D = GetComponent<MyLight2D>();
        clock = ServiceLocator.Get<Clock>();
        if (height == 0 || width == 0)
        {
            Debug.LogWarning("未设置长宽");
            Destroy(gameObject);
        }
    }

    private void OnEnable()
    {
        GenerateShape();
        clock.TimeChange += ChangeShadow;
    }

    private void OnDisable()
    {
        clock.TimeChange -= ChangeShadow;
    }

    private void Start()
    {
        ChangeShadow();
    }

    private void GenerateShape()
    {
        float halfWidth = width / 2;
        switch (bearing)
        {
            case EBearing.North:
            case EBearing.South:
                bottom1 = new Vector3(-halfWidth, 0);
                bottom2 = new Vector3(halfWidth, 0);
                windowOutline.Add(bottom1);
                windowOutline.Add(bottom2);
                windowOutline.Add(new Vector3(-halfWidth, height));
                windowOutline.Add(new Vector3(halfWidth, height));
                break;
            case EBearing.West:
            case EBearing.East:
                bottom1 = new Vector3(0, halfWidth);
                bottom2 = new Vector3(0, -halfWidth);
                windowOutline.Add(bottom1);
                windowOutline.Add(bottom2);
                break;
        }
        comparer = new GeometryTool.Comparer_Vector2_Clockwise(Vector2.zero);
    }

    private void ChangeShadow()
    {
        Vector3 shadowLine = SunSimulateTool.CalculateShadowOfStick(height, clock.DateTime.HourOfDay);
        if (shadowLine != Vector3.zero && LightInDoor(shadowLine.RemoveZ().ToAngle()))
        {
            lightOutline.Clear();
            lightOutline.AddRange(windowOutline);
            lightOutline.Add(bottom1 + shadowLine);
            lightOutline.Add(bottom2 + shadowLine);
            myLight2D.Light.enabled = true;
            lightOutline.Sort(comparer);
            myLight2D.SetOutline(lightOutline);
        }
        else
            myLight2D.Light.enabled = false;
    }

    private bool LightInDoor(float angle)
    {
        return bearing switch
        {
            EBearing.North => angle > 90f && angle < 270f,
            EBearing.West => angle > 180f,
            EBearing.South => angle < 90f || angle > 270f,
            EBearing.East => angle < 180f,
            _ => false
        };
    }
}
